// pages/my/bindTelephone/bindTelephone.js
var $ = require('../../../utils/ajax.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loadingHidden: true,
    sendACClass: 'weui-vcode-btn',
    sendAcColor: '',
    sendACText: '获取验证码',
    telephone: '',//记录表单填写的手机号，用来发送验证码，因为验证码发送并不是触发表单提交，只能通过事件获取
    code: '', //验证码
    isSuccess:false
  },
  inputTel: function (e) {  
    console.log(e);
    let _this = this;
    _this.setData({
      telephone:e.detail.value
    })
    
  },
  /**
   * 获取验证码
   */
  sendAC: function (e) {
    var that = this;
    if (!that.data.sendACClass) {//如果是禁用状态则不刻意点击(类名为空表示禁用)
      return;
    }
    if (that.data.telephone == "" || that.data.telephone.length != 11) {//表单验证
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: "请填写合法手机号！"
      });
    } else {//验证通过发送验证码
      //开始60秒倒计时 倒计时期间不允许再次发送
      var timeOut = 60;
      that.setData({
        sendACText: timeOut + '再次发送',
        sendACClass: ''
      });
      var t1 = setInterval(() => {
        timeOut--;
        that.setData({
          sendACText: '还剩' + timeOut + '秒'
        });
        if (timeOut == 0) {//倒计时结束 停止计时器
          clearTimeout(t1);
          that.setData({
            sendACText: '获取验证码',
            sendACClass: 'weui-vcode-btn'
          });
        }
      }, 1000);
      console.log("开始发送验证码。。。");
      //开始请求验证码
      wx.request({
        url: getApp().data.app_server + '/weixin/authCode', //仅为示例，并非真实的接口地址
        data: {
          phoneNumber: that.data.telephone
        },
        header: {
          'content-type': 'application/json' 
        },
        dataType: 'json',
        success: function (res) {
          console.log(res);
          that.setData({
            code: res.data.id //设置验证码
          });
        },
        fail:function(res){
          wx.showToast({
            title: '请求超时',
            icon: 'none',
            duration: 2000
          })
        }
      });
    }
  },
  /**
 * 提交数据
 */
  formSubmit: function (e) {
    console.log(e);
    var that = this;
    var warn = "";//弹框时提示的内容
    var flag = true;//判断信息输入是否完整
    if (e.detail.value.telephone == "" || e.detail.value.telephone.length != 11) {
      warn = "请填写合法手机号！";
    } else if (e.detail.value.vcode == "") {
      warn = "请填写验证码！";
    } else {
      flag = false;//若必要信息都填写，则不用弹框，且页面可以进行跳转
      that.setData({
        loadingHidden: false
      });
      this.doLogin(that, e.detail.value);
    }

    //如果信息填写不完整，弹出输入框
    if (flag == true) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: warn
      })
    }
  },
  /**
   * 登录程序
   */
  doLogin(that, formData) {
    wx.login({
      success: function (res) {
        if (res.code) {
          formData.code = res.code;
          that.doExeMethod(that, formData);
        } 
      }
    });
  },
  //  //发起登录请求
  doExeMethod(that, formData) {
    //发起登录请求
    $.post({
      url: getApp().data.app_server + '/weixin/login',
      data: {
        code: formData.code,
        phoneNumber: formData.telephone,
        yzm: formData.vcode
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
    }).then((res) => {
      console.log(res);
      let msg = res.data.msg;
      if (res.data.code == 200) {//登录成功
        let token = res.data.msg.id;
        this.getUnionid(token)
        msg = '登陆成功';
        wx.setStorageSync("token", token);//将token写入手机
        wx.setStorageSync("permissions", res.data.msg.permissions);//将权限写入手机
        wx.setStorageSync("userId", res.data.msg.userId);
        app.data.token = token;
        for (var i = 0; i < app.data.loginState.length; i++) {//观察者模式，轮训里面的方法
          var fun = app.data.loginState[i];
          fun(app.data.loginStateParams[i]);
        }
      }
      wx.showModal({//无论成功失败都会提示响应信息
        title: '提示',
        showCancel: false,
        content: msg,
        success: (r) => {
          if (res.data.code == 200) {//登录成功会返回个人中心页面
            wx.reLaunch({
              url: '/pages/my/index'
            })
          }
          that.setData({
            loadingHidden: true
          })
        }
      });
    }).catch((err) => {
      console.log(err);
      that.setData({
        loadingHidden: true
      })
      wx.showToast({
        title: '请求超时',
        icon: 'none',
        duration: 2000
      })
    });
  },
  // 获取用户unionid
  getUnionid (token) {
    console.log('token', token)
    //引导用户授权
    wx.getUserInfo({
      data: { withCredentials: true },
      success: res => {
        $.post({
          url: getApp().data.app_server + '/weixin/updateUser',
          data: {
            token: token,
            iv: res.iv,
            encryptedData: res.encryptedData
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
        }).then(r => {
          console.log(r)
        })
      },
      fail: () => {//授权失败,跳转授权页面
        wx.navigateTo({
          url: "/pages/authorization/index"
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})